package com.kepler.social.web.sharding;

import com.kepler.social.common.utils.ShardingHashUtils;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


public class EmailShardingAlgorithm implements ComplexKeysShardingAlgorithm<String> {

    private static final String EMAIL = "email";

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<String> shardingValue) {
        if (!shardingValue.getColumnNameAndRangeValuesMap().isEmpty()) {
            throw new RuntimeException("不支持除了=和in的操作");
        }
        // 获取订单id
        Collection<String> emails = shardingValue.getColumnNameAndShardingValuesMap().getOrDefault(EMAIL, new ArrayList<>(1));
        List<String> tableNames = emails.stream()
                // 对可用的表名求余数，获取到真实的表的后缀
                .map(email -> ShardingHashUtils.toSharding(email, availableTargetNames.size()))
                // 转换成string
                .map(String::valueOf)
                // 获取到真实的表
                .map(tableSuffix -> availableTargetNames.stream().filter(targetName -> targetName.endsWith(tableSuffix)).findFirst().orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return tableNames;
    }
}
